package com.lance.answer.gui.answer.gk.answer.lms.batch.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.google.common.collect.Maps;
import com.lance.answer.gui.answer.Util;
import com.lance.answer.gui.answer.gk.answer.lms.batch.dto.LmsWatchDTO;
import com.lance.answer.gui.answer.gk.answer.lms.dto.CourseInfo;
import com.lance.answer.gui.answer.gk.answer.lms.util.LmsUtil;
import com.lance.answer.util.HttpUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.TimeUnit;

@Slf4j
public class GetUserCourseInfoByJsonTask extends Thread {


    private final String driverPath;
    private final LinkedBlockingDeque<LmsWatchDTO> watchDTOS;

    public GetUserCourseInfoByJsonTask(String driverPath, LinkedBlockingDeque<LmsWatchDTO> watchDTOS) {
        this.driverPath = driverPath;
        this.watchDTOS = watchDTOS;
    }

    @SneakyThrows
    @Override
    public void run() {

        while (watchDTOS.size() > 0) {
            LmsWatchDTO lmsWatchDTO = watchDTOS.take();
            String userName = lmsWatchDTO.getUsername();
            String password = lmsWatchDTO.getPassword();
            log.info("任务：{} 剩余 {} 行 用户名：{} 密码：{}",
                    Thread.currentThread().getName(), watchDTOS.size(), userName, password);
            System.err.println("执行任务11111");
            run(driverPath, lmsWatchDTO);
        }

        if (watchDTOS.size() == 0) {
            log.info("课程所有用户均已执行完毕，系统将在20min后结束");
            TimeUnit.MINUTES.sleep(20);
            return;
        }
    }


    public static void run(String driverPath, LmsWatchDTO lmsWatchDTO) throws Exception {


        String userName = lmsWatchDTO.getUsername();
        String pwd = lmsWatchDTO.getPassword();
        String teacher = lmsWatchDTO.getTeacher();

        ChromeDriver driver = Util.getDriver(driverPath);

        try {

            String url = "https://menhu.pt.ouchn.cn/site/ouchnPc/index";
            driver.get(url);
            Thread.sleep(3000);

            LmsUtil.login(driver, userName, pwd);

            // FIXME TODO driver.get("https://lms.ouchn.cn/user/courses#/");
            driver.get("https://lms.ouchn.cn/user/courses#/");
            Thread.sleep(10000);

            CourseInfo courseInfo = getUserCourseInfo(driver);
            System.err.println(courseInfo);

            List<CourseInfo.CoursesDTO> courses = courseInfo.getCourses();

            Map<Long, String> courseMap = Maps.newHashMap();
            for (CourseInfo.CoursesDTO coursesDTO : courses) {
                courseMap.put(coursesDTO.getId(), coursesDTO.getDisplayName());
            }

            File file = new File("libs//lmsCourseInfo//" +teacher+"//"+ userName + ".json");

            FileUtils.write(file, JSONObject.toJSONString(courseMap, SerializerFeature.PrettyFormat), "utf-8");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                driver.close();
                Util.switchToFirst(driver);
                driver.quit();
            } catch (Exception e) {

            }
        }


    }


    private static CourseInfo getUserCourseInfo(WebDriver driver) {
        // FIXME  page_size =10 是有问题的。
        String getUrl = "https://lms.ouchn.cn/api/my-courses?conditions=%7B%22status%22:%5B%22ongoing%22%5D,%22keyword%22:%22%22%7D&fields=id," +
                "name,course_code,department(id,name),grade(id,name),klass(id,name),course_type,cover,small_cover," +
                "start_date,end_date,is_started,is_closed,academic_year_id,semester_id,credit,compulsory,second_name," +
                "display_name,created_user(id,name),org(is_enterprise_or_organization),org_id,public_scope,course_attributes" +
                "(teaching_class_name,copy_status,tip,data),audit_status,audit_remark,can_withdraw_course,imported_from," +
                "allow_clone,is_instructor,is_team_teaching,academic_year(id,name),semester(id,name)," +
                "instructors(id,name,email,avatar_small_url),is_master,is_child,has_synchronized,master_course(name)" +
                "&page=1&page_size=10";

        String cookie = Util.getCookie(driver.manage().getCookies());
        Map<String, String> heads = Maps.newHashMap();
        heads.put("referer", "https://lms.ouchn.cn/user/courses");
        heads.put(":method", "GET");
        heads.put(":authority", "lms.ouchn.cn");
        heads.put("cookie", cookie);
        heads.put(":path", "/api/my-courses?conditions=%7B%22status%22:%5B%22ongoing%22%5D,%22keyword%22:%22%22%7D&fields=id,name,course_code,department(id,name),grade(id,name),klass(id,name),course_type,cover,small_cover,start_date,end_date,is_started,is_closed,academic_year_id,semester_id,credit,compulsory,second_name,display_name,created_user(id,name),org(is_enterprise_or_organization),org_id,public_scope,course_attributes(teaching_class_name,copy_status,tip,data),audit_status,audit_remark,can_withdraw_course,imported_from,allow_clone,is_instructor,is_team_teaching,academic_year(id,name),semester(id,name),instructors(id,name,email,avatar_small_url),is_master,is_child,has_synchronized,master_course(name)&page=1&page_size=10");
        heads.put("accept", "application/json, text/plain, */*");


        String result = null;
        try {
            result = HttpUtil.get(getUrl, cookie, heads);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return JSON.parseObject(result, CourseInfo.class);

    }

}
